package com.yuedou.api.controller.product;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yuedou.api.constant.ResponseCode;
import com.yuedou.api.controller.platform.BaseController;
import com.yuedou.api.entity.product.OrderAppraise;
import com.yuedou.api.entity.product.OrderAppraiseImg;
import com.yuedou.api.entity.product.ProductOrder;
import com.yuedou.api.entity.product.ProductOrderInfo;
import com.yuedou.api.entity.wxuser.User;
import com.yuedou.api.service.product.OrderAppraiseImgService;
import com.yuedou.api.service.product.OrderAppraiseService;
import com.yuedou.api.service.product.ProductOrderInfoService;
import com.yuedou.api.service.product.ProductOrderService;
import com.yuedou.api.service.wxuser.UserService;
import com.yuedou.api.util.GsonResultBean;
import com.yuedou.api.util.ImagesFiler;
import com.yuedou.api.util.OssUtil;
import com.yuedou.api.util.Tools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  用户技能相关接口
 *@Date 2025-01-17
 */
@Component
@RestController
@RequestMapping("/orderAppraise")//url:模块/资源/{}/细分
public class OrderAppraiseController extends BaseController {

    @Resource
    private OrderAppraiseService orderAppraiseService;
    @Resource
    private OrderAppraiseImgService orderAppraiseImgService;
    @Resource
    private UserService userService;
    @Resource
    private ProductOrderService productOrderService;
    @Resource
    private ProductOrderInfoService productOrderInfoService;

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址

    /** 评论列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "orderAppraise/list 接收的参数： "+requestParam);
            System.out.println("orderAppraise/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;

            List<OrderAppraise> appraises = orderAppraiseService.selectByMerId(mer_id,pageIndex,pageSize);
            if(appraises!=null){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",appraises.size(),appraises),false,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",new ArrayList()),false,true);
            }

        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /** 发表评论
     * @param
     * @throws Exception
     */
    @PostMapping(value="/pubAppraise")
    public JSONObject pubAppraise(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "orderAppraise/pubAppraise 接收的参数： "+requestParam);
            System.out.println("orderAppraise/pubAppraise 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            long order_id = jsonRequest.containsKey("order_id") ? jsonRequest.getLong("order_id") : 0;
            long info_id = jsonRequest.containsKey("info_id") ? jsonRequest.getLong("info_id") : 0;
            int star = jsonRequest.containsKey("star") ? jsonRequest.getInt("star") : 5;
            String content = jsonRequest.containsKey("content") ? jsonRequest.getStr("content") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前用户不存在"),true,true);
            }
            ////订单状态 0 - 未支付   1 - 已支付，待发货  2 - 已发货， 待收货  3 - 已收货，待评价 4 - 已评价  5 - 订单取消  6 - 已申请退货  7 - 同意退货  8 - 退货完成 9 - 拒绝退货
            ProductOrder order = productOrderService.findById(order_id);
            if(order == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不存在"),true,true);
            }else if(order.getUserId() != user_id){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"当前订单不属于您"),true,true);
            }

            if(content.equals("")){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"评论内容不能为空"),true,true);
            }

            if(order.getOrderType() == 0 || order.getOrderType() == 4) {
                ProductOrderInfo orderInfo = productOrderInfoService.findById(info_id);
                if (orderInfo != null) {
                    if (order.getStatus() == 0 || order.getStatus() == 1) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "当前订单未支付!"), true, true);
                    } else if (order.getStatus() == 3) {
                        //订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销
                        // 4 - 已评价  5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                        int id = addAppraise(order,content,orderInfo.getProductId(),orderInfo.getSkuId(),star);
                        if (id > 0) {
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "发表成功", id), true, false);
                        } else {
                            return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "发表评论失败"), true, true);
                        }
                    } else if (order.getStatus() == 4) {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "当前订单已取消"), true, true);
                    } else {
                        return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "当前状态不能评价"), true, true);
                    }
                }
            }
//            else{
//                int id = addAppraise(order,content,0L,0L,star);
//                if (id > 0) {
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "发表成功", id), true, false);
//                } else {
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "发表评论失败"), true, true);
//                }
//            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    private int addAppraise(ProductOrder order,String content,Integer productId,Integer skuId,int star){
        OrderAppraise appraise = new OrderAppraise();
        appraise.setOrderId(order.getId());
        appraise.setAppraiseType(0);
        appraise.setContent(content);
        appraise.setCreateTime(new Date());
        appraise.setProductId(productId);
        appraise.setSkuId(skuId);
        appraise.setIsAnonymous(0);
        appraise.setPraiseStar(star);
        appraise.setState(1);//0 - 未审核状态  1 - 审核通过  显示在评价列表里  2 - 审核失败（有违禁内容）
        appraise.setKeyWord("");
        boolean ret = orderAppraiseService.save(appraise);
        if(ret){
            productOrderService.updateOrderState(order,4);
        }
        int id = appraise.getId();
        return id;
    }

    /** 发表评论
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public JSONObject uploadImg(@RequestParam("appraise_id") int appraise_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            OrderAppraise appraise = orderAppraiseService.findById(appraise_id);
            if(appraise == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "评论不存在"), true, true);
            }

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    int index = 0;
                    for(String key : maps.keySet()) {
                        MultipartFile certurl = maps.get(key);
                        if (!certurl.isEmpty()) {
                            String prefix = certurl.getOriginalFilename().substring(certurl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "appraise_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certurl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_ORDER_APPRAISE_IMGS;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;

                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certurl.getBytes());
                                        out.flush();
                                        out.close();

//                                        OssUtil.upload(certurl.getInputStream(),fileName,upload_type);

                                        ImagesFiler.imageResize(filePath,filePath);

                                        OrderAppraiseImg img = new OrderAppraiseImg();
                                        img.setImgUrl(img_key);
                                        img.setAppraiseId(appraise_id);
                                        img.setSort(index);
                                        orderAppraiseImgService.save(img);
                                    }
                                } catch (IOException e) {
                                    result = Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                    e.printStackTrace();
                                }
                            }
                            index++;
                        }

                    }
                }
            }
            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "发表成功"), true, true);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
